<?php

namespace app\model;

use think\facade\Db;
use think\Model;

class OrderReviewsModel extends Model {

    protected $table ="order_reviews";

    protected $pk = 'review_id';
    private $cacheKey="review:id:";

    private $cacheTime=51840000;


    /*
   * 获取total
   * */
    public function getTotal($where=[]){
        return Db::name('order_reviews')->where($where)->count();
    }


    /*
     * 获取list
     * */
    public function getList($where,$page = null,$limit = null,$orderField = null,$orderType = "ASC"){

        $obj =  Db::name('order_reviews')->field("review_id")->where($where);

        if(!empty($field) ) {
            $obj = $obj->field($field);
        }

        if(!empty($page) && !empty($limit)){
            $obj = $obj->page($page, $limit);
        }

        if(!empty($orderField) && !empty($orderType)){
            $obj = $obj->order($orderField, $orderType);
        }

        $list = $obj->select();

        if($list){
            $return = [];
            foreach($list as $item){
                $return[] = $this->getInfo($item['review_id']);
            }
            return $return;
        }
        return [];
    }



    /*
* 获取订单状态详情
* */
    public function getInfo($id){
        $cacheKey = $this->cacheKey.$id;
        $redisModel = new RedisModel();
        $info = $redisModel->get($cacheKey);
        if($info){
            $info =  json_decode($info,true);
        }else{
            $info = Db::name('order_reviews')->find($id);
            //整理
            $info["review_thumbnail"] = !empty($info["review_thumbnail"]) ? json_decode($info["review_thumbnail"],true) :"";
            $info["user_info"] = !empty($info["user_info"]) ? json_decode($info["user_info"],true) :"";
            $info["product_info"] = !empty($info["product_info"]) ? json_decode($info["product_info"],true) :"";
            $info["spec_info"] = !empty($info["spec_info"]) ? json_decode($info["spec_info"],true) :"";
            $redisModel->set($cacheKey,json_encode($info,256),$this->cacheTime);
        }

        $info['review_content'] = !empty($info['review_content']) ? base64_decode($info['review_content']) : "";
        $where=[];
        $where[] = ['p_review_id','=',$id];
        $where[] = ['review_status','<>',-1];
        $info["childList"] = $this->getList($where);
        return $info;
    }


    /*
    * 保存数据
    * */
    public function addOne($data){
        return Db::name('order_reviews')->insertGetId($data);
    }

    /*
    * 修改运单号
    * */
    public function updateOne($id, $data){
        $where[] = ["review_id","=",$id];
        return Db::name('order_reviews')->where($where)->update($data);
    }

}